#encoding=utf-8

from django.shortcuts import render
from models import BlogsPost
import models
from django.shortcuts import render_to_response
from django.shortcuts import HttpResponse

from django.http import HttpResponseRedirect

import django

import json

from models import MagicCardPracticeData

# Create your views here.
def index(request):
    blog_list = BlogsPost.objects.all()
    return render_to_response('index.html', {'posts': blog_list})


def updata(request):
    return HttpResponseRedirect('/cgi-bin/cgi.py')


def post_magiccard_data(request):

    #process json data

    #write json data to sqlite3

    return HttpResponse('ok')


def test_get(request):
    # GET
    # http://localhost:8888/?name=xh&key=123
    name = request.GET.get('name','xxx')
    pwd = request.GET.get('pwd','xxx')
    txt = "name:"+name+","+"pwd:"+pwd
    return HttpResponse(txt)

def test_post2(request):
    # origin_record = request.POST.get('origin_record','xxx')
    # practice_record = request.POST.get('practice_record','xxx')
    # cost_time = request.POST.get('cost_time','xxx')
    # record_time = request.POST.get('record_time','xxx')

    # obj = {'name':name,'pwd':pwd}
    # encodedjson = json.dumps(obj)

    # html = "<html><body> user:%s</body></html>" % name

    # practice_record = received_json_data['practice_record']

    # process magiccard data
    # if request.method == 'POST':
    #    received_json_data = json.loads(request.body)
    #    file = '/json_data/my.json'
    #    fp = open(file,'w+')
    #    fp.write(received_json_data)
    #    fp.close()
    #    return  HttpResponse(received_json_data)
    # else:
    #    return HttpResponse("<html><body>no json received</html></body>")
    pass


def post(request):
    #POST param
    received_json_data = {}
    if request.method == 'POST':
       received_json_data = json.loads(request.body)

    origin = received_json_data['origin_record']

    practice = ''
    cost = int(received_json_data['cost_time'])
    record = received_json_data['record_time']
    #import time,datetime
    #string = datetime.datetime.fromtimestamp(time.mktime(time.strptime(record_time,"%Y/%m/%d %H:%M:%S")))
    data = MagicCardPracticeData(origin_record=origin,practice_record=practice,cost_time=cost,record_time=record)
    #中文显示，需要encoding-utf-8
    #过滤器，过滤相同时间的记录，避免重复插入。
    #时间：20160103，至此，iOS客户端上传数据备份的功能就初步做好了。现在就是完善这个Django应用了。ios 客户端只做最核心的功能。
    if not MagicCardPracticeData.objects.filter(record_time=data.record_time).exists():
        data.save()
        return HttpResponse('server:record exist,OK!')

    return HttpResponse('server:record insert,OK!')


def home(request):
    return HttpResponse("Hello,django !version:"+str(django.VERSION))